package training_progress

import (
	"context"
	"net/http"

	"encoding/json"

	"go.uber.org/zap"

	"internal_training_be/db"
	"internal_training_be/user_mgt"
)

func Run (){

	zap.L().Sugar().Info("---->training_progress/training_progress.go is run")

	adminMiddlewares := user_mgt.AdminImpl{}

	http.Handle("/api/queryAllEmployeeTrainingSituation",adminMiddlewares.CorsMiddleware(adminMiddlewares.AuthMiddleware(http.HandlerFunc(getAllEmployeeTrainingProgress))))

	http.Handle("/api/signIn",adminMiddlewares.CorsMiddleware(adminMiddlewares.AuthMiddleware(http.HandlerFunc(setProgressStatus))))

	http.Handle("/api/progressMark", adminMiddlewares.CorsMiddleware(adminMiddlewares.AuthMiddleware(http.HandlerFunc(setProgressStatus))))
}

func getAllEmployeeTrainingProgress(w http.ResponseWriter, r *http.Request) {

	zap.L().Sugar().Info("---->training_progress/getAllEmployeeTrainingProgress")

	var msg string

	// 读取请求上下文
	ctx := r.Context()

	// 获取管理员ID
	adminID := ctx.Value("adminId").(string)
	if adminID == "" {
		zap.L().Sugar().Error("获取管理员ID为空")
		return
	}

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
		return
	}

	if dbConn == nil {
		zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
		return
	}

	defer dbConn.Release()

	// 查询所有员工的培训进度
	rows, err := dbConn.Query(context.Background(),"SELECT * FROM s_training_system.t_training_progress")
	if err != nil {
		zap.L().Sugar().Errorf("查询所有员工的培训进度失败, err: %v", err.Error())
		return
	}

	defer rows.Close()

	var trainingProgressData []map[string]interface{}

	for rows.Next() {
		var progressID string
		var employeeID string
		var employeeName string
		var courseID string
		var courseName string
		var status int

		err := rows.Scan(&progressID, &employeeID, &status, &courseID)
		if err != nil {
			zap.L().Sugar().Errorf("获取培训进度失败, err: %v", err.Error())
			return
		}

		// 获取数据库连接
		dbConn, err := db.GetDBConn()
		if err != nil {
			zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
			return
		}

		if dbConn == nil {
			zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
			return
		}

		defer dbConn.Release()

		// 获取员工姓名
		err = dbConn.QueryRow(context.Background(), "SELECT username FROM s_training_system.t_employee WHERE id = $1", employeeID).Scan(&employeeName)
		if err != nil {
			zap.L().Sugar().Errorf("获取员工姓名失败, err: %v", err.Error())
			return
		}

		// 获取课程名称
		err = dbConn.QueryRow(context.Background(), "SELECT course_name FROM s_training_system.t_course WHERE course_id = $1", courseID).Scan(&courseName)
		if err != nil {
			zap.L().Sugar().Errorf("获取课程名称失败, err: %v", err.Error())
			return
		}

		trainingProgressData = append(trainingProgressData, map[string]interface{}{
			"progressID": progressID,
			"employeeID": employeeID,
			"employeeName": employeeName,
			"courseID": courseID,
			"courseName": courseName,
			"status": status,
		})

	}
	

	json.NewEncoder(w).Encode(map[string]interface{}{
		"msg": msg,
		"code": 0,
		"data": trainingProgressData,
	})

}

func setProgressStatus(w http.ResponseWriter, r *http.Request) {

	zap.L().Sugar().Info("---->training_progress/setProgressStatus")

	var msg string

	// 读取请求上下文
	ctx := r.Context()

	// 获取管理员ID
	adminID := ctx.Value("adminId").(string)
	if adminID == "" {
		zap.L().Sugar().Error("获取管理员ID为空")
		return
	}

	// 获取数据库连接
	dbConn, err := db.GetDBConn()
	if err != nil {
		zap.L().Sugar().Errorf("获取数据库连接失败, err: %v", err.Error())
		return
	}

	if dbConn == nil {
		zap.L().Sugar().Error("获取数据库连接失败, dbConn为空")
		return
	}

	defer dbConn.Release()

	// 获取请求参数
	var rBody struct {
		EmployeeID string `json:"employeeID"`
		CourseID string `json:"courseID"`
		SetStatusCode int `json:"setStatusCode"`
	}

	err = json.NewDecoder(r.Body).Decode(&rBody)

	if err != nil {
		msg = `解析请求体发生错误,未找到"employeeID"或"courseID"或"setStatusCode"字段,err: ` + err.Error()
		zap.L().Sugar().Error(msg)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"msg": msg,
			"code": 1,
		})
		return
	}

	// 查询表中是否存在该员工的培训进度
	var progressID string

	err = dbConn.QueryRow(context.Background(), "SELECT progress_id FROM s_training_system.t_training_progress WHERE employee_id = $1 AND course_id = $2", rBody.EmployeeID, rBody.CourseID).Scan(&progressID)
	if err != nil {
		// 如果不存在，则插入一条新的记录
		_, err = dbConn.Exec(context.Background(), "INSERT INTO s_training_system.t_training_progress (employee_id, status) VALUES ($1, $2)", rBody.EmployeeID, rBody.SetStatusCode)
		if err != nil {
			msg = "插入培训进度失败, err: " + err.Error()
			zap.L().Sugar().Error(msg)
			json.NewEncoder(w).Encode(map[string]interface{}{
				"msg": msg,
				"code": 1,
			})
			return
		}

		msg = "签到成功"
		json.NewEncoder(w).Encode(map[string]interface{}{
			"msg": msg,
			"code": 0,
		})

		return
	}

	// 如果存在，则更新记录
	_, err = dbConn.Exec(context.Background(), "UPDATE s_training_system.t_training_progress SET status = $1 WHERE progress_id = $2", rBody.SetStatusCode, progressID)
	if err != nil {
		msg = "更新培训进度失败, err: " + err.Error()
		zap.L().Sugar().Error(msg)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"msg": msg,
			"code": 1,
		})
		return
	}

	switch rBody.SetStatusCode {
		case 0:
			msg = "取消签到成功"
			break
		case 1:
			msg = "签到成功"
			break
		case 2:
			msg = "培训完成"
			break
		default:
			msg = "未知状态"
			break
	}

	json.NewEncoder(w).Encode(map[string]interface{}{
		"msg": msg,
		"code": 0,
	})
}